<template>

    <el-dialog :title="title"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :visible.sync="open" custom-class="form-dialog " append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="单词" prop="word">
                  <el-input v-model="form.word" placeholder="请输入单词" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="中文" prop="cn">
                  <el-input v-model="form.cn" placeholder="请输入中文" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="音标" prop="ipa">
                  <el-input v-model="form.ipa" placeholder="请输入音标" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="教材" prop="bookId">
                  <el-select v-model="form.bookId" placeholder="请选择教材" filterable>
                    <el-option
                      v-for="dict in dictData('sys_entity_book')"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"

                    ></el-option>
                  </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="年级" prop="grade">
                  <el-select v-model="form.grade" placeholder="请选择年级" filterable>
                    <el-option
                      v-for="dict in dictData('grade')"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"

                    ></el-option>
                  </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="模块" prop="module">
                  <el-select v-model="form.module" placeholder="请选择模块" filterable>
                    <el-option
                      v-for="dict in dictData('sys_entity_module')"
                      :key="dict.dictValue"
                      :label="dict.dictLabel"
                      :value="dict.dictValue"

                    ></el-option>
                  </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="单元" prop="unit">
                  <number type="integer" v-model="form.unit" placeholder="请输入单元" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="图片" prop="image">
                  <single-image-upload v-model="form.image"/>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="音频" prop="audio">
                  <el-input v-model="form.audio" placeholder="请输入音频" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="场景" prop="sentence">
                  <el-input v-model="form.sentence" placeholder="请输入场景" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="场景翻译" prop="sentenceTrans">
                  <el-input v-model="form.sentenceTrans" placeholder="请输入场景翻译" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="场景音频" prop="sentenceAudio">
                  <el-input v-model="form.sentenceAudio" placeholder="请输入场景音频" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="columnSpan">
                <el-form-item label="难度" prop="difficulty">
                    <el-rate v-model="form.difficulty"></el-rate>
                </el-form-item>
            </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

</template>

<script>
import * as fltrpWordService from "@/api/service/fltrp/FltrpWordService";
import { Loading } from 'element-ui';

export default {
  name: "WordForm",
  props:{
    item:{
        type: Object
    }
  },
	dictionaries: ['sys_entity_book', 'grade', 'sys_entity_module'],
  data() {
    return {
      // 栅栏 24
      columnSpan: 24,
      // 表单初始化完成
      formInitialed: false,
      // 页面/弹窗标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        word: [
          { required: true, message: "单词不能为空", trigger: "blur" }
        ],
        cn: [
          { required: true, message: "中文不能为空", trigger: "blur" }
        ],
        ipa: [
          { required: true, message: "音标不能为空", trigger: "blur" }
        ],
        bookId: [
          { required: true, message: "教材不能为空", trigger: "change" }
        ],
        grade: [
          { required: true, message: "年级不能为空", trigger: "change" }
        ],
        module: [
          { required: true, message: "模块不能为空", trigger: "change" }
        ],
        unit: [
          { required: true, message: "单元不能为空", trigger: "blur" }
        ],
        difficulty: [
          { required: true, message: "难度不能为空", trigger: "blur" }
        ],
        viewVolume: [
          { required: true, message: "出现次数不能为空", trigger: "blur" }
        ],
        correct: [
          { required: true, message: "正确次数不能为空", trigger: "blur" }
        ],
        displayIndex: [
          { required: true, message: "排序值不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.open = true;
  },
  mounted(){
    // 获取 form并加入loading，避免网络差造成假死现象
    this.$nextTick(() => {
      if(this.$refs.form){
        if(!this.dataInitialed){
          this.loadingInstance = Loading.service({
            target: this.$refs.form.$el,
            fullscreen: false
          });
        }
      }
    })

    if(this.item.id){
      this.title = "修改外研社单词";
      this.handleUpdate(this.item.id);
    }
    else{
      this.title = "添加外研社单词";
      this.handleAdd();
      this.formInitialed = true;
    }
  },
  computed:{
    dataInitialed(){
      return this.formInitialed;
    }
  },
  watch:{
      open(newVal){
        if(!newVal){
          this.$emit('update:item', null);
        }
      },
      dataInitialed(val){
        if(val && this.loadingInstance){
          this.loadingInstance.close();
        }
      }
  },
  methods: {

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        word: null,
        cn: null,
        ipa: null,
        bookId: null,
        grade: null,
        module: null,
        unit: null,
        image: null,
        audio: null,
        sentence: null,
        sentenceTrans: null,
        sentenceAudio: null,
        difficulty: null,
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
    },
    /** 修改按钮操作 */
    handleUpdate(id) {
      this.reset();
      fltrpWordService.get(id).then(resp => {
        this.form = resp;
      }).finally(()=>{
        this.formInitialed = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 使用副本，避免数据污染
          let form = JSON.parse(JSON.stringify(this.form));

          let loadingInstance = Loading.service({
            target: this.$refs.form.$el,
            fullscreen: false,
            text: '提交中'
          });
          if (this.item.id != null) {
            fltrpWordService.update(form).then(response => {
              this.$modal.success("修改成功");
              this.open = false;
              this.$emit('success', form);
            }).catch(err => {
			        console.error(err);
            }).finally(()=>{
              loadingInstance.close();
            });
          } else {
            fltrpWordService.add(form).then(response => {
              this.$modal.success("新增成功");
              this.open = false;
              this.$emit('success', form);
            }).catch(err => {
			        console.error(err);
            }).finally(()=>{
               loadingInstance.close();
            });
          }
        }
      });
    }
  }
};
</script>
